package com.gzsxy.esjy.sign.socket;

import com.alibaba.fastjson.JSON;
import com.gzsxy.esjy.sign.InnerSignCode;
import com.gzsxy.esjy.sign.async.AsyncWsClient;
import com.gzsxy.esjy.sign.cache.SignCacheManager;
import com.gzsxy.esjy.sign.dto.AndroidSignProtocolDto;
import com.gzsxy.esjy.sign.dto.InnerSignDto;
import com.gzsxy.esjy.sign.service.GSSignBusinessService;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

/**
 * 安卓 websocket 消息处理
 * @author zhangxiaolong
 * @since 2022/7/15
 */
@Component
@Slf4j
public class AndroidAsyncWsCallBack implements AsyncWsCallBack {

    @Autowired
    private SignCacheManager cacheManager;

    @Autowired
    private GSSignBusinessService gsSignBusinessService;

    @Override
    public void doResponse(AsyncWsClient asyncWsClient, Object msg) {
        try {
            String text = ((TextWebSocketFrame) msg).content().toString(Charset.defaultCharset());
            AndroidSignProtocolDto androidSignProtocolDto = JSON.parseObject(text, AndroidSignProtocolDto.class);
            log.info("收到签名板信息:{}", JSON.toJSONString(androidSignProtocolDto));
            String response = "response";
            if (response.equals(androidSignProtocolDto.getP_type())) {
                log.info("回复信息,不做处理");
                return;
            }

            gsSignBusinessService.androidSignOk(androidSignProtocolDto, asyncWsClient.getTaskId());
        } catch (Exception e) {
            log.error("AndroidAsyncWsCallBack::", e);
        }
    }

    @Override
    public void connected(AsyncWsClient asyncWsClient) {
        InnerSignDto innerSignDto = getSignDto(asyncWsClient, "与签名板连接成功", InnerSignCode.CONNECTED_CODE);
        gsSignBusinessService.deviceStatus(innerSignDto);
    }

    @Override
    public void disConnected(AsyncWsClient asyncWsClient) {
        cacheManager.clearSignByRequestId(asyncWsClient.getRequestId(), true, true);
        InnerSignDto innerSignDto = getSignDto(asyncWsClient, "与签名板连接断开", InnerSignCode.DISCONNECT_ERROR_CODE);
        gsSignBusinessService.deviceStatus(innerSignDto);
    }

    @Override
    public void exception(AsyncWsClient asyncWsClient, Throwable cause) {
        cacheManager.clearSignByRequestId(asyncWsClient.getRequestId(), true, true);
        InnerSignDto innerSignDto = getSignDto(asyncWsClient, "与签名板连接异常断开：" + cause.getMessage(), InnerSignCode.EX_DISCONNECT_ERROR_CODE);
        gsSignBusinessService.deviceStatus(innerSignDto);
    }

    @Override
    public void heartbeat(AsyncWsClient asyncWsClient, IdleStateEvent event) {

    }
}
